
local Component = import("..Component")
local SimpleEvent = class("SimpleEvent", Component)

function SimpleEvent:ctor()
    SimpleEvent.super.ctor(self, "SimpleEvent")
    self.listeners_ = {}
    self.nextListenerHandleIndex_ = 0
end

function SimpleEvent:addEventListener(eventName, listener)
    assert(type(eventName) == "string" and eventName ~= "",
        "SimpleEvent:addEventListener() - invalid eventName")
    eventName = eventName
    if self.listeners_[eventName] == nil then
        self.listeners_[eventName] = {}
    end

    self.nextListenerHandleIndex_ = self.nextListenerHandleIndex_ + 1
    local handle = tostring(self.nextListenerHandleIndex_)
    self.listeners_[eventName][handle] = listener
    return handle
end

function SimpleEvent:dispatchEvent(name,...)
    local eventName = tostring(name)

    if self.listeners_[eventName] == nil then return end

    local currentListeners = self.listeners_[eventName]
    for handle, listener in pairs(currentListeners) do
    	listener(...)
    end
end

function SimpleEvent:removeEventListener(handleToRemove)
    for eventName, listenersForEvent in pairs(self.listeners_) do
        for handle, _ in pairs(listenersForEvent) do
            if handle == handleToRemove then
                listenersForEvent[handle] = nil
            end
        end
    end
end


function SimpleEvent:removeEventListenersByEvent(eventName)
    self.listeners_[eventName] = nil
end

function SimpleEvent:removeAllEventListeners()
    self.listeners_ = {}
end

function SimpleEvent:hasEventListener(eventName)
    eventName = tostring(eventName)
    local t = self.listeners_[eventName]
    for _, __ in pairs(t) do
        return true
    end
    return false
end


function SimpleEvent:exportMethods()
    self:exportMethods_({
        "addEventListener",
        "dispatchEvent",
        "removeEventListener",
        "removeEventListenersByEvent",
        "removeAllEventListeners",
        "hasEventListener",
    })
    return self.target_
end

function SimpleEvent:onBind_()
end

function SimpleEvent:onUnbind_()
end

return SimpleEvent
